import os
import re
import json
import numpy as np
import cantera as ct

from pathlib import Path

def is_numeric_string(input_string):
    # Regular expression pattern for numeric string with decimal point or scientific expression
    pattern = r'^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$'

    # Check if the input string matches the pattern
    if re.match(pattern, input_string):
        return True
    else:
        return False

mechanism = 'Okafor2018_s59r356.yaml'
min_temperature = 300

def interp_T(arr, dT=1):
    arr = arr[arr[:, 0].argsort()]

    T = arr[:, 0]

    new_T = np.arange(np.min(T)//dT*dT, np.max(T)//dT*dT + dT, dT)

    interpolated_time_arr = np.copy(new_T)

    for i in range(1, arr.shape[1]):
        y = arr[:, i]

        new_y = np.interp(new_T, T, y)

        interpolated_time_arr = np.column_stack((interpolated_time_arr, new_y))
        
    print(interpolated_time_arr.shape)
    final_arr = np.row_stack((interpolated_time_arr, arr))
    
    print(final_arr.shape)

    # return final_arr
    return arr
    #return interpolated_time_arr

print("STARTING DATA COLLECTION\n")
gas = ct.Solution(mechanism)
TPspecies_list = ['T', 'p'] + gas.species_names

data_tag = '1Dflame'
main_dir = Path('.')
case_dirs = [glob_finding for glob_finding in main_dir.rglob("*") if glob_finding.is_dir() and 'postProcessing' in glob_finding.name]
print(case_dirs)
for case_dir in case_dirs:
    lineA_dir = case_dir / 'lineSampleA'
    lineB_dir = case_dir / 'lineSampleB'
    time_dirs = [glob_finding for glob_finding in lineA_dir.rglob("*") if glob_finding.is_dir() and is_numeric_string(glob_finding.name)]
    print(time_dirs)
    
    all_arrs = []
    
    for time_dir in time_dirs:
        time = time_dir.name
        lineA_files = list(time_dir.glob("*lineA*"))
        
        if len(lineA_files) == 1:
            lineA_file = lineA_files[0]
            print(f"Found file: {lineA_file}")
        else:
            raise ValueError(f"Expected exactly one file containing 'lineA', but found {len(lineA_files)}.")
        
        lineB_time_dir = lineB_dir / time
        lineB_files = list(lineB_time_dir.glob("*lineB*"))
        
        if len(lineB_files) == 1:
            lineB_file = lineB_files[0]
            print(f"Found file: {lineB_file}")
        else:
            raise ValueError(f"Expected exactly one file containing 'lineB', but found {len(lineB_files)}.")
        
        arr_A = np.loadtxt(lineA_file)[:, 1:]
        arr_B = np.loadtxt(lineB_file)[:, 1:]
        print(f"Data dimensions: {arr_A.shape} and {arr_B.shape}")

        if arr_A.shape[0] == arr_B.shape[0]:
            arr = np.concatenate((arr_A, arr_B), axis=1)  # Concatenate along columns
            all_arrs.append(interp_T(arr))
            print(f"Concatenated array shape: {arr.shape}")
        else:
            raise ValueError("The number of rows in arr_A and arr_B do not match.")
    
    if all_arrs:
        data_array = np.concatenate(all_arrs, axis=0)
        
        # data_array = data_array[data_array[:, 0] >= min_temperature]
        
        print(f"Total data array shape: {data_array.shape}")
        np.save(f"{data_tag}_{case_dir.parent.name}_raw.npy", data_array)
        print(f"Data saved to {data_tag}_{case_dir.parent.name}.npy")
